<template>
  <section>
    <div class="filter-container">
        <common-input @keyup.enter.native="handleFilter" class="w200 ml10" placeholder="套装名称" v-model="listQuery.keyword" />
        <el-button size="mini" class="ml10" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
        <el-button size="mini" class="ml10" @click="handleCreate" type="primary" icon="el-icon-plus">新增</el-button>
    </div>
    <el-tabs size="mini" :before-leave='leaveTab' v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="出售中" name="1"></el-tab-pane>
      <el-tab-pane label="已下架" name="2"></el-tab-pane>
    </el-tabs>
    <el-alert
            v-if="ids&&ids.length>0"
            show-icon>
        <template slot="title">
            <span>已选择 {{ids.length}} 项</span> <el-button @click="clear()" type="text">清空</el-button> 
            <template v-if="!isSelect">
                <el-button v-if="activeName=='1'" @click="down()" type="text">批量下架</el-button> 
                <el-button v-else-if="activeName=='2'" @click="up()" type="text">批量上架</el-button>
            </template>
            <template v-else>
                <el-button  @click="select()" type="text">选择</el-button> 
            </template>
        </template>
    </el-alert>
    <el-table ref="dataTable" :height="tableHeight" :data="list"
                        @sort-change="tblSort"
                        @selection-change="selectChange"
                style="width: 100%">
            <el-table-column
                    fixed
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column align="right" width="80" label="排序" sortable="custom" prop="order_num">
                <template slot-scope="scope">
                    <span>{{scope.row.orderNum}}</span>
                    <i @click="editOrder(scope.row)" class="el-icon-edit ml10" style="cursor:pointer;color:#F4222D;"></i>
                </template>
            </el-table-column>
            <el-table-column align="left" label="套装编号">
                <template slot-scope="scope">
                    <span>{{scope.row.id}}</span>
                </template>
            </el-table-column>
            <el-table-column align="left" label="" width="120">
                <template slot-scope="scope">
                    <span><img :src="scope.row.listImgUrl" style="width:80px;cursor:pointer;" @click="viewPic(scope.row)" /></span>
                </template>
            </el-table-column>
            <el-table-column align="left" label="套装">
                <template slot-scope="scope">
                    <span>{{scope.row.name}}</span>
                </template>
            </el-table-column>
            <el-table-column width="100" align="right" label="市场价" sortable="custom" prop="price">
                <template slot-scope="scope">
                    <span>￥{{scope.row.price}}</span>
                </template>
            </el-table-column>
            <el-table-column width="100" align="right" label="商品数" sortable="custom" prop="item_count">
                <template slot-scope="scope">
                    <span>{{scope.row.itemCount}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="创建时间" width="150" sortable="custom" prop="created_at">
                <template slot-scope="scope">
                    <span>{{scope.row.createdAt}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作" 
                    fixed="right" v-if="!isSelect">
                <template slot-scope="scope">
                    <span>
                        <el-dropdown class="ml10">
                        <el-button

                                type="text">
                            更多<i class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item @click.native="handleUpdate(scope.row)">编辑</el-dropdown-item>
                            <el-dropdown-item v-if="scope.row.canUp==1" @click.native="handleUp(scope.row)">上架</el-dropdown-item>
                            <el-dropdown-item v-if="scope.row.canDown==1" @click.native="handleDown(scope.row)">下架</el-dropdown-item>
                            <el-dropdown-item v-if="scope.row.canDelete==1" @click.native="handleDelete(scope.row)">删除</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                    </span>
                </template>
            </el-table-column>
    </el-table>
        <div class="pagination-container">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNum" :page-sizes="[20,30, 50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
        </div>

    <el-dialog title="编辑排序" :visible.sync="dialogOrderVisible" :close-on-click-modal="false" width="300px">
        <el-form :model="orderForm" ref="orderForm" label-width="80px">
            <el-form-item label="排序" prop="orderNum">
                <el-input size="mini" type="number" placeholder="" maxlength="3" v-model="orderForm.orderNum" />
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button size="mini" @click="dialogOrderVisible=false">取消</el-button>
            <el-button :loading="orderLoading" size="mini" type="primary" @click="okOrder">确定</el-button>
        </div>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="900px">
        <el-form :model="form" :rules="rules" ref="form" label-width="150px">
            <el-form-item label="套装名称" prop="name">
                <common-input v-model="form.name" placeholder="请输入套装名称" maxlength="10" />
            </el-form-item>
            <el-form-item label="套装图片" prop="listImgUrl">
                <pic-sel style="float:left" v-model="form.listImgUrl" :maxNum="1" />
            </el-form-item>
            <el-form-item label="市场价" prop="price">
                <el-input type="number" size="mini" class="w200" v-model="form.price" placeholder="请输入市场价" maxlength="10" />
            </el-form-item>
            <el-form-item label="排序" prop="orderNum">
                <common-input v-model="form.orderNum" class="w60" maxlength="3" />
            </el-form-item>
            <el-form-item label="选择商品">
                <el-button size="mini" class="ml10" @click="addItem()" type="primary" icon="el-icon-plus">选择商品</el-button>
                <table class="ikd-input-table ik-table-layout-fixed">
                    <thead>
                    <tr>
                        <th nowrap>序号</th>
                        <th nowrap>商品名称</th>
                        <th nowrap>商品规格</th>
                        <th nowrap>售价</th>
                        <th nowrap>原始库存</th>
                        <th nowrap>库存</th>
                        <th nowrap style="width:100px;">操作</th>
                    </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item, idx) in form.items" :key="item.id">
                            <td>{{idx+1}}</td>
                            <td>{{item.title}}</td>
                            <td>{{item.attribute}}</td>
                            <td>{{item.price}}</td>
                            <td>{{item.skuInventory}}</td>
                            <td><el-input type="number" size="mini" class="w100" v-model="item.inventory" maxlength="10" /></td>
                            <!-- <td><el-input type="number" size="mini" class="w100" v-model="item.orderNum" maxlength="10" /></td> -->
                            <td>
                                <el-button type="text"  @click="addItem(idx)">编辑</el-button>
                                <el-button type="text"  @click="removeItem(idx)">删除</el-button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button size="mini" @click="dialogFormVisible=false">取消</el-button>
            <el-button size="mini" v-if="dialogStatus=='create'" type="primary" @click="create('form')">确定</el-button>
            <el-button size="mini" v-else type="primary" @click="update('form')">确定</el-button>
        </div>
    </el-dialog>
    
    <el-dialog title="选择商品" :visible.sync="dialogProductVisible" :close-on-click-modal="false" width="1000px">
        <product-list :formData.sync="productSelectForm" @okSkuSelect="okSelectProduct" />
        <div slot="footer" class="dialog-footer">
            <el-button size="mini" type="primary" @click="dialogProductVisible=false">关闭</el-button>
        </div>
    </el-dialog>

  </section>
</template>

<script>
    import {
        isIntegerNotMust
    } from '../../utils/validator'
    import {
        package_save,
        package_list,
        package_delete,
        package_update_order,
        package_detail,
        package_up,
        package_down
    } from '../../api/product';
    import Viewer from 'viewerjs';
    import 'viewerjs/dist/viewer.css';
    export default {
        components: {
            'pic-sel': () => import('../../components/PicSel/index'),
            'product-list': () => import('../../components/Product/list'),
        },
        props: {
            formData: Object
        },
        data() {
            return {
                dialogProductVisible: false,
                productSelectForm: {
                    is_select: true,
                    is_sku: true,
                },
                rules: {
                    name: [
                        {
                            required: true,
                            message: '请输入套装名称',
                            trigger: 'blur'
                        }
                    ],
                    price: [
                        {
                            required: true,
                            message: '请输入套装市场价',
                            trigger: 'blur'
                        }
                    ],
                    listImgUrl: [
                        {
                            required: true,
                            message: '请选择套装图片',
                            trigger: 'blur'
                        }
                    ],
                    orderNum: [
                        {
                            validator: isIntegerNotMust,
                            trigger: 'blur'
                        }
                    ]
                },
                form: {
                    id: undefined,
                    name: undefined,
                    listImgUrl: undefined,
                    price: undefined,
                    items: [],
                },
                dialogStatus: '',
                dialogFormVisible: false,
                textMap: {
                    update: '编辑套装',
                    create: '新增套装'
                },

                isSelect: false,
                viewerId: null,
                orderLoading: false,
                tableHeight: 200,
                list: null,
                listLoading: true,
                listQuery: {
                    pageNum: this.$route.query.pageNum || 1,
                    pageSize: this.$route.query.pageSize || 20,
                    agency: undefined,
                    keyword: this.$route.query.keyword,
                    orderCol: "",
                    orderAsc: "",
                    status: '1',
                },
                total: null,
                activeName: '1',
                currentId: 0,
                checkLoading: false,
                dialogOrderVisible: false,
                orderForm: {
                    id: 0,
                    orderNum: 0,
                },
                productForm: {
                    id: 0,
                    hasSku: 0,
                    skuInfo: [],
                    inventory: 0,
                },
                dialogStockVisible: false,
                stockLoading: false,
                ids: [],
                selectedIdx: undefined,
            }
        },
        watch: {
            formData: {
                immediate: true,
                handler (val) {
                    this.isSelect = val.is_select;

                    // console.log(val)
                }
            }
        },
        mounted() {
            const that = this

            window.onresize = () => {

                return (() => {

                    that._getTableHeight()

                })()
            }
        },
        created() {
            this._getTableHeight();
            this.getList();
        },
        methods: {
            okSelectProduct(result) {
                this.dialogProductVisible = false;
                if(!this.form.items) {
                    this.form.items = [];
                }
                // console.log("idx: " + this.selectedIdx)
                if(typeof this.selectedIdx != "undefined") {
                    this.form.items[this.selectedIdx].title = result.title;
                    this.form.items[this.selectedIdx].attribute = result.attribute;
                    this.form.items[this.selectedIdx].productId = result.productId;
                    this.form.items[this.selectedIdx].skuId = result.skuId;
                    this.form.items[this.selectedIdx].price = result.price;
                    this.form.items[this.selectedIdx].skuInventory = result.skuInventory;
                } else {
                    this.form.items.push(result);
                }
                console.log(result)
                // product_add_to_page(
                //     {
                //         pageId: this.pageId,
                //         ids: ids
                //     }
                // ).then((res)=>{
                //     this.$message.success("商品已加入专区");
                //     this.getList();
                //     this.dialogProductVisible = false;
                // }).catch((err)=>{

                // })
                // console.log(ids)
            },
            addItem(idx) {
                this.selectedIdx = idx;
                this.dialogProductVisible = true;
            },
            removeItem(idx) {
                this.$confirm('确定删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        let final_items = [];
                        this.form.items.forEach((item, i)=>{
                            if(i != idx) {
                                final_items.push(item);
                            }
                        })

                        this.form.items = final_items;
                    }).catch(()=>{});
            },
            handleCreate() {
                this.resetTemp();
                this.dialogStatus = 'create';
                this.dialogFormVisible = true;
            },
            create(formName) {
                const set = this.$refs;
                set[formName].validate(valid => {
                    if (valid) {
                        if(!this.form.orderNum) {
                            this.form.orderNum = 0;
                        }
                        package_save(this.form)
                            .then(() => {
                                this.dialogFormVisible = false;
                                this.getList();
                                this.$message.success("套装创建成功");
                            })
                    } else {
                        return false;
                    }
                });
            },
            update(formName) {
                const set = this.$refs;
                set[formName].validate(valid => {
                    if (valid) {
                        if(!this.form.orderNum) {
                            this.form.orderNum = 0;
                        }

                        package_save(this.form).then(() => {
                            this.dialogFormVisible = false;
                            this.getList();
                            this.$message.success("套装更新成功");
                        });
                    } else {
                        return false;
                    }
                });
            },
            resetTemp() {
                this.form = {
                    id: undefined,
                    name: undefined,
                    listImgUrl: undefined,
                    price: undefined,
                    items: [],
                };
            },
            _getTableHeight() {
                this.tableHeight = window.innerHeight - 250
            },
            getList() {
                this.listLoading = true;
                package_list(this.listQuery).then(response => {
                    this.list = response.data.list;
                    this.total = response.data.total;
                    this.listLoading = false;
                })
            },
            viewPic(row) {
                if(row.imgUrls) {
                    let all_pic = row.imgUrls.split(",");
                    $("#pic_viewer").html("");
                    if(all_pic && all_pic.length > 0) {
                        all_pic.forEach((item, idx)=>{
                            var str  = '<li style="width:100%;">';
                            str += '<img rel-src="' + item + '" src="' + item + '">';
                            str += '</li>';
                            $("#pic_viewer").append(str);
                        })
                    }
                    this.viewerId && this.viewerId.destroy()
                    this.viewerId = new Viewer(document.getElementById('pic_viewer'));
                    $('#pic_viewer').find("img").eq(0).trigger("click")
                }
            },
            handleFilter() {
                this.listQuery.pageNum = 1;
                this.getList();
            },
            handleSizeChange(val) {
                this.listQuery.pageSize = val;
                this.getList();
            },
            handleCurrentChange(val) {
                this.listQuery.pageNum = val;
                this.getList();
            },
            handleClick(tab, event) {
                this.listQuery.status = this.activeName;
                this.handleFilter();
            // console.log(this.activeName)
            },
            leaveTab(activeName, oldActiveName) {
            // console.log(activeName)
            // return false;
            },
            handleUpdate(row) {
                package_detail(row.id)
                    .then(response => {
                        this.form = response.data;
                        this.dialogFormVisible = true;
                        this.dialogStatus = 'update';
                    });
            },
            handleDelete(row) {
                this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        package_delete(row.id)
                            .then(() => {
                                this.$message.success("套装删除成功");
                                this.getList();
                            });
                    }).catch(()=>{});
            },
            handleDetail(row) {
                let {href} = this.$router.resolve({path: '/goods_detail?id=' + row.id});
                window.open(href, '_blank');
            },
            dialogClose() {
                this.$refs.form.resetFields();
            },
            tblSort(d) {
                this.listQuery.orderCol = d.prop;
                this.listQuery.orderAsc = d.order;

                this.handleFilter();
            },
            editOrder(row) {
                this.orderForm.id = row.id;
                this.orderForm.orderNum = row.orderNum;

                // console.log(this.orderForm)
                this.dialogOrderVisible = true;
            },
            okOrder() {
                this.orderLoading = true;
                package_update_order(this.orderForm).then((res)=>{
                    this.orderLoading = false;
                    this.dialogOrderVisible = false;
                    this.$message.success("排序已更新");

                    this.getList();
                }).catch((err)=>{
                    this.orderLoading = false;
                })
            },
            editStock(row) {
                package_detail(row.id).then((res)=>{
                    this.productForm.id = res.data.id;
                    this.productForm.hasSku = res.data.hasSku;
                    this.productForm.inventory = res.data.inventory;
                    this.productForm.skuInfo = res.data.skuInfo;

                    this.dialogStockVisible = true;

                    console.log(this.productForm)
                }).catch((err)=>{

                })
            },
            makeMinStock() {
                let p = 0;
                if(this.productForm.skuInfo && this.productForm.skuInfo.length > 0) {
                    this.productForm.skuInfo.forEach((item)=>{
                        if(item.inventory) {
                            p += Number(item.inventory) || 0
                        }
                    })
                }
                this.productForm.inventory = p;
            },
            okStock() {
                this.stockLoading = true;
                package_update_stock(this.productForm).then((res)=>{
                    this.stockLoading = false;
                    this.dialogStockVisible = false;
                    this.$message.success("库存已更新");

                    this.getList();
                }).catch((err)=>{
                    this.stockLoading = false;
                })
            },
            selectChange(selection) {
                this.ids = [];
                if(selection && selection.length > 0) {
                    selection.forEach((item)=>{
                        this.ids.push(item.id)
                    })
                }
                // console.log(this.ids)
            },
            clear() {
                this.$refs.dataTable.clearSelection();
            },
            up(ids) {
                if(!ids || ids.length < 1) {
                    ids = this.ids;
                }
                this.$confirm('确定上架?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        package_up({
                            ids: ids
                        })
                            .then(() => {
                                this.$message.success("套装上架成功");
                                this.getList();
                            });
                    }).catch(()=>{});
            },
            down(ids) {
                if(!ids || ids.length < 1) {
                    ids = this.ids;
                }
                this.$confirm('确定下架?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        package_down({
                            ids: ids
                        })
                            .then(() => {
                                this.$message.success("套装下架成功");
                                this.getList();
                            });
                    }).catch(()=>{});
            },
            handleUp(row) {
                this.up([row.id]);
            },
            handleDown(row) {
                this.down([row.id]);
            },
            select() {
                this.$emit('okSelect', this.ids);
            }
        }
    };
</script>
<style lang="scss" scoped>
</style>
